<template>
  <div>
    <validator name="verifyEmailForm">
      <form role="form" name="Form" class="col-md-8 col-md-offset-2 form-margin">
        <div class="form-group">
          <label for="newEmail">我们向<span class="primary">{{state.newEmail}}</span>发送了验证邮件</label>
          <label>请输入邮件中的验证码</label>
          <div class="input-group">
            <input type="text" autocomplete="off" class="form-control" id="chkCode" initial="off" detect-change="off" v-validate:chk-code="['required']" v-model="state.chkCode" placeholder="请输入验证码">
            <span class="input-group-btn">
              <button class="btn btn-default" :disabled="resendTime!==0" v-on:click.prevent="resend" >重新发送<span v-show="resendTime">{{'('+resendTime+')'}}</span></button>
            </span>
          </div>
          <div>
            <error-template v-show="$verifyEmailForm.chkCode.required">{{$verifyEmailForm.chkCode.required}}</error-template>
          </div>
        </div>
        <button class="btn btn-primary pull-right" v-on:click.prevent="validChkCode">下一步</button>
      </form>
    </validator>
  </div>
</template>
<script>
/**
 * @author guocailee
 */

import imgCheckCode from 'components/ImgCheckCode.vue'
import { verifymailbindcaptcha } from 'src/api/check'
import { updateEmail } from 'src/store/actions/security'
export default {
  props: {
    state: {
      required: true,
      type: Object
    }
  },
  data () {
    let resendTime = 60
    let timeoutId = null
    return {
      resendTime,
      timeoutId
    }
  },
  vuex: {
    actions: { updateEmail }
  },
  components: {
    imgCheckCode
  },
  methods: {
    timeStart () {
      var self = this
      self.resendTime = 60
      if (self.timeoutId) {
        return
      }
      self.timeoutId = setInterval(() => {
        self.resendTime --
        if (self.resendTime <= 0) {
          clearInterval(self.timeoutId)
          self.timeoutId = null
        }
      }, 1000)
    },
    resend () {
      this.timeStart()
      this.$dispatch('sendmailbindcaptcha')
    },
    validChkCode() {
      let self = this
      self.$validate(true, () => {
        if (self.$verifyEmailForm.invalid) {
          return
        }
        verifymailbindcaptcha(self.state)
        .then(data => self.updateEmail(self.state.newEmail))
        .then(data => self.$dispatch('nexStep'))
        .catch(message => self.$notify.error(message))
      })
    }
  },
  ready () {
    this.timeStart()
  }
}
</script>